import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_li_ke_jie/core/http/http.dart';
import 'package:flutter_li_ke_jie/entity/app_product.dart';
import 'package:flutter_li_ke_jie/entity/app_product_list.dart';
import 'package:flutter_li_ke_jie/entity/app_user.dart';

import '../../constant/api_constant.dart';
import '../../core/utils/toast.dart';
import '../../entity/base_response.dart';
import '../../router/router.dart';
import '../../utils/log.dart';
import '../../utils/nav_key.dart';
import '../../utils/navigator_util.dart';
import '../../utils/sputil.dart';

///首页数据
class HomeModel with ChangeNotifier{
  int currentIndex = 0;//当前索引
  List<AppProduct> homeAppProductList = [];//当前首页产品
  List<AppProduct> headerVipAppProductList =[AppProduct(),AppProduct()];//当前首页VIP产品


  //切换
  void switchIndex(int index){
    currentIndex = index;
    notifyListeners();
  }

  //获取当前用户的首页产品列表
  void getHomeProductList(){
    String? userId = SPUtil.getUserId();
    if(userId!=null&&userId.isNotEmpty){
      Map<String, dynamic> params = {};
      params["pageNum"] = 1;
      params["pageSize"] = 10;
      params["userId"] = userId;
      XHttp.get(CURRENT_PRODUCT_LIST,params).then((response){
        Log.e("首页产品数据返回:$response");
        if(response["code"]==200){
          AppProductList appProductList = AppProductList.fromJson(response);
          //数据解析
          if(appProductList!=null){
            homeAppProductList = appProductList.appProduct!;
            headerVipAppProductList = appProductList.headerAppProduct!;
          }
          notifyListeners();
        }else{
          ToastUtils.error(response["msg"]);
        }
      });
    }else{
      //用户信息未null返回到登录页
      Future.delayed(Duration(seconds:0)).then((onValue)  {
        BuildContext? context = NavKey.navKey.currentState?.overlay?.context;
        if(context!=null){
          NavigatorUtil.goAndFinishAll(context, LOGIN_PAGE);
        }
      });
    }
  }


  //产品点击统计
  void productClick(AppProduct appProduct){
    //获取用户信息
    AppUser? appUser = SPUtil.getUserInfo();
    if(appUser!=null){
      //统计
      Map<String,dynamic> map = {
        "userId":appUser.userId,
        "phone":appUser.phone,
        "productId":appProduct.productId,
        "productName":appProduct.name,
        "channelId":appUser.channelId,
        "channelName":appUser.channelName,
        "channelCode":appUser.channelCode
      };
      //上传
      XHttp.postJson(PRODUCT_CLICK_API,map,false).then((response){
        Log.e("统计成功");
      });
    }
  }
}


